import Vue from 'vue'
import axios from 'axios'
import store from '@/store'
import notification from 'ant-design-vue/es/notification'
import {
  ADMIN_ID
} from '@/store/mutation-types'

// 创建 axios 实例
const service = axios.create({
  baseURL: '/yzm-web-api', // api base_url
  timeout: 6000 // 请求超时时间
})

const err = (error) => {
  if (error.response) {
    const data = error.response.data
    const token = Vue.ls.get(ADMIN_ID)
    if (error.response.status === 403) {
      notification.error({
        message: 'Forbidden',
        description: data.message
      })
    }
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      notification.error({
        message: 'Unauthorized',
        description: 'Authorization verification failed'
      })
      if (token) {
        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            window.location.reload()
          }, 1500)
        })
      }
    }
  }
  return Promise.reject(error)
}
service.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
service.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded'
service.defaults.transformRequest = [function (data) {
  let ret = ''
  for (const it in data) {
    ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
  }
  return ret
}]
// request interceptor
service.interceptors.request.use(config => {
  return config
}, err)

// response interceptor
service.interceptors.response.use((response) => {
  let res
  if (response.data && typeof response.data === 'string') {
    res = JSON.parse(response.data)
  } else {
    res = response.data
  }
  switch (res.status) {
    case '200':
      return res
    case 200:
      return res
    case '40001':
      // localStorage.clear()
      // window.location.reload()
      break
    case 40001:
    // localStorage.clear()
    // window.location.reload()
      break
    default:
      return res
  }
}, err)
export {
  service as axios
}
